<template>
	<view>
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="cu-custom">
			<view class="cu-bar search fixed "  style="height:60px;background-color: #f0f0f0; padding-top: 20px;">
				<view class="action">
					<text class="cuIcon-back text-gray" @tap="goback"></text>
				</view>
				<view style="font-size: 120%;">
					{{friendInfo.friendUsername}}
				</view>
				<view class="action">
					<text class="cuIcon-more" @tap="goDislogDetail" data-target="bottomModal"></text>
				</view>
			</view>
		</view>
		
		<view class="cu-chat" id="liaotian" style="padding-top: 80px;">
			<view v-for="(message,index) in msgList" :key="index">
				<!-- 本人消息记录 -->
				<view v-if="message.userId==userInfo.id" class="cu-item self">
					<view class="main">
						<view class="content bg-green shadow">
							<text>{{message.msg}}</text>
						</view>
					</view>
					<view class="cu-avatar radius" :style="'background-image:url('+userInfo.faceImage+');'"></view>
					<view class="date">{{message.time}}</view>
				</view>

				<!-- 朋友消息记录 -->
				<view v-else class="cu-item">
					<view class="cu-avatar radius" :style="'background-image:url('+friendInfo.friendFaceImage+');'"></view>
					<view class="main">
						<view class="content shadow">
							<text>{{message.msg}}</text>
						</view>
					</view>
					<view class="date ">{{message.time}}</view>
				</view>
			</view>

		</view>

		<view id="sendBar" class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view>
			<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10" @focus="InputFocus"
			 @blur="InputBlur" v-model="message" />
			<view class="action">
				<text class="cuIcon-emojifill text-grey"></text>
			</view>
			<button :class="message!=null?'bg-green':'bg-gray'" class="cu-btn shadow" @click="sendMsg()">发送</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				websocket: null,
				InputBottom: 0,
				friendInfo: null,
				userInfo: null,
				message: null,
				msgList: []
			};
		},
		onInit() {
			console.log('onSHow')
		},
		onUnload() {
			console.log('onUnLoad')

			var that = this

			// 重新设置websocket的onMessage处理函数
			this.$tool.WEBSOCKET._callbacks.message = [function(e) {
				var msg = (JSON.parse(e.data)).chatMsg.msg
				var sendUserId = (JSON.parse(e.data)).chatMsg.sendUserId
				var time = that.$tool.getNowDate()
				var userId = that.$tool.getStorageSync('userInfo').id

				// 接收到的 '消息快照' 保存为 "未读" false
				that.$tool.saveChatSnapShot(userId, sendUserId, msg, false, time)

				// 将接收到的聊天消息保存到 localStorage 中
				that.$tool.saveChatHistory(userId, sendUserId, msg, time, 1) // 发送者ID，接收者ID，消息,时间
			}]
		},
		onShow() {
			// 获取与当前用户的本地聊天记录
			this.getMsgHistory();
		},
		onLoad(options) {
			console.log('onload')
			
			// 重置websocket的onMessage处理函数
			this.$tool.WEBSOCKET._callbacks.message = []
			
			setTimeout(() => {
				uni.pageScrollTo({
					scrollTop: 99999,
					duration: 0
				});
			}, 50);
			
			// 获取用户信息
			this.userInfo = this.$tool.getStorageSync("userInfo")
			
			this.websocket = this.$tool.WEBSOCKET
			
			this.initWebSocket();
			
			// 获取上一个页面传过来的好友信息
			this.friendInfo = JSON.parse(decodeURIComponent(options.user))
			
			
			// 获取与当前用户的本地聊天记录
			this.getMsgHistory();
		},
		watch: {
			/* 使用watch来响应数据的变化 */
			msgList(newVal, oldVal) {
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 99999,
						duration: 0
					});
				}, 50);
			}
		},
		methods: {
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},

			// 初始化 WebSocket
			initWebSocket() {
				this.websocket.onMessage((e) => {
					var msg = (JSON.parse(e.data)).chatMsg.msg
					var sendUserId = (JSON.parse(e.data)).chatMsg.sendUserId
					var time = this.$tool.getNowDate()

					if (sendUserId == this.friendInfo.friendUserId) { // 是当前与之聊天的用户所发消息
						// 将接受的聊天消息追加到界面上
						this.msgList.push({
							msg: msg,
							time: time,
							userId: sendUserId
						})

						// 当前所接收到的是 "当前好友" 所发的消息，所以消息快照保存为 "已读" true
						this.$tool.saveChatSnapShot(this.userInfo.id, sendUserId, msg, true, time)

					} else {
						// 当前所接收到的是 "别的好友" 所发的消息，所以消息快照保存为 "未读" false
						this.$tool.saveChatSnapShot(this.userInfo.id, sendUserId, msg, false, time)
					}

					// 将接收到的聊天消息保存到 localStorage 中
					this.$tool.saveChatHistory(this.userInfo.id, sendUserId, msg, time, 1) // 发送者ID，接收者ID，消息,时间
				})
			},

			// 发送消息
			sendMsg() {
				var that = this
				var msg = this.message
				var time = this.$tool.getNowDate()

				if (msg != null && msg != '') {

					// 构建chatMsg
					var chatMsg = new this.$tool.ChatMsg(this.userInfo.id, this.friendInfo.friendUserId, msg, null)

					// 构建dataContent
					var dataContent = new this.$tool.DataContent(this.$tool.CHAT, chatMsg, null)

					// websocket 发送消息给server
					this.websocket.send({
						data: JSON.stringify(dataContent),
						success: function() {

							// 播放发送提示音
							that.playSendMsgAudio()

							// 发送成功后，将聊天消息保存到 localStorage 中
							that.$tool.saveChatHistory(that.userInfo.id, that.friendInfo.friendUserId, msg, time, 0) // 发送者ID，接收者ID，消息,时间

							// 追加信息到面板上
							that.msgList.push({
								msg: msg,
								time: time,
								userId: that.userInfo.id
							})

							// 保存聊天的快照记录，对于发送者来讲，该条消息已经被读了
							that.$tool.saveChatSnapShot(that.userInfo.id, that.friendInfo.friendUserId, msg, true, time)
						},
						fail: function() {
							that.$tool.sendToast('websocket-消息发送失败！')
						}
					})

					this.message = null

				} else {
					this.$tool.sendToast("消息不能为空!")
				}
			},

			// 获取本地消息记录
			getMsgHistory() {
				var chatList = this.$tool.getChatHistory(this.userInfo.id, this.friendInfo.friendUserId)
				this.msgList = []
				// 封装数组
				chatList.forEach(item => {
					this.msgList.push({
						userId: item.sendUserId,
						msg: item.msg,
						time: item.time
					})
				})
			},

			// 播放发送消息铃声
			playSendMsgAudio() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '../../static/mp3/send.mp3';
				innerAudioContext.volume = 0.1
				innerAudioContext.onPlay(() => {
					//console.log('开始播放');
				});
			},

			// 播放接收消息的铃声
			playReceiveMsgAudio() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '../../static/mp3/send.mp3';
				innerAudioContext.volume = 0.1
				innerAudioContext.onPlay(() => {
					//console.log('开始播放');
				});
			},

			// 跳转聊天详情页面
			goDislogDetail() {
				uni.navigateTo({
					url:`../chat/chatInfo?user=${encodeURIComponent(JSON.stringify(this.friendInfo))}`
				})
			},

			goback() {
				uni.navigateBack(-1)
			},
		}
	}
</script>

<style>
	.status_bar {
		position: fixed;
		height: var(--status-bar-height);
		width: 100%;
	}

	page {
		padding-bottom: 100upx;
	}
</style>
